import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import FaButton from 'widget/FaButton';
import { H3 } from 'widget/PageHead';
import { FaTrashAlt } from 'react-icons/fa';
import LoadingPage from 'widget/LoadingPage';
import BaseModal from 'component/Modals/BaseModal';
import RestService from 'service/RequestServices/RestService';
import AdministratorBaseContent from './AdministratorBaseContent';

class AdministratorEditModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      labels: []
    };
    this.modalRef = React.createRef();
    this.deleteRest = this.deleteRest.bind(this);
  }

  componentDidMount() {
    this.getRest();
  }

  getRest() {
    let { labels, loading } = this.state;
    const { table, id } = this.props;
    RestService.fetchRest(table, id).then(data => {
      labels = Object.keys(data).map(key => {
        return {
          label: key,
          value: data[key],
          type: typeof data[key],
          disabled: true
        };
      });
      loading = false;
      this.setState({ loading, labels });
    });
  }

  deleteRest() {
    let { loading } = this.state;
    loading = true;
    this.setState({ loading });
    const { table, id } = this.props;
    RestService.deleteRest(table, id).then(data => {
      console.log('data', data);
      location.href = location.href;
    });
  }

  render() {
    const { loading /* , labels */ } = this.state;
    return (
      <BaseModal onClose={this.props.onClose}>
        {loading ? (
          <LoadingPage />
        ) : (
          <AdministratorBaseContent
            labels={[]}
            ref={this.modalRef}
            header={
              <H3>
                <FormattedMessage id="admin.if.delete" />
              </H3>
            }
            onSubmit={this.deleteRest}
            footer={[
              <FaButton fa={<FaTrashAlt />} theme="danger" bold onClick={this.deleteRest}>
                <FormattedMessage id="admin.delete.it" />
              </FaButton>
            ]}
          />
        )}
      </BaseModal>
    );
  }
}

AdministratorEditModal.propTypes = {
  table: PropTypes.string.isRequired,
  id: PropTypes.number.isRequired,
  onClose: PropTypes.func.isRequired
};

export default AdministratorEditModal;
